<template>
  <div
    class="data-edit-box"
    element-loading-text="数据加载中"
    element-loading-spinner="el-icon-loading"
    v-loading="pageLoading"
  >
    <div class="data-page-header">
      <div class="header-title">{{ formDesc.title }}</div>
      <div class="btnList">
        <RPButton v-if="!disabled" optType="reset" style="margin-right: 10px" @click="hide" text="取消" />
        <RPButton
          v-if="isCreate || isEdit"
          style="margin-right: 10px"
          optType="create"
          type="info"
          @click="downLoadModel"
          text="下载模板"
        />
        <RPButton
          v-if="isCreate || isEdit"
          style="margin-right: 10px"
          optType="create"
          type="info"
          :loading="loading"
          @click="save"
          text="保存"
        />
        <RPButton
          v-if="isCreate || isEdit"
          style="margin-right: 10px"
          optType="create"
          type="info"
          @click="submit"
          :loading="loading"
          text="提交"
        />
        <RPButton
          v-if="showProcessButton && formData.processId"
          style="margin-right: 10px"
          optType="create"
          type="info"
          @click="goApproval"
          :text="!isView ? '查看流程' : '审批'"
        />
      </div>
    </div>
    <div class="data-edit-content">
      <Row>
        <Col span="24">
          <Form
            ref="formValidate"
            :model="formData"
            label-position="right"
            :rules="ruleValidate"
            :label-width="300"
            :disabled="disabled"
          >
            <div class="indicatorItem" v-for="(item, index) in formDesc.content" :key="index">
              <div class="titleItem">
                <Row :gutter="10">
                  <Col span="11">
                    <Form-item :label="item.label" :label-width="210" :prop="item.value">
                      <div slot="label" style="display: contents;">
                        {{ item.indicatorName }}
                        <Tooltip v-if="item.tip" transfer max-width="800" :content="item.tip" placement="right" slot>
                          <Icon type="ios-help-circle" />
                        </Tooltip>
                      </div>
                      <InputNumber v-if="item.showInput" :value="setValue(item.value)" size="large" :disabled="true" />
                    </Form-item>
                  </Col>
                  <Col span="8" v-if="item.showFile">
                    <div class="upload">
                      <Upload
                        v-if="!disabled"
                        ref="upload"
                        :action="uploadUrl"
                        :headers="uploadHeaders"
                        :data="uploadData"
                        accept=".xls,.xlsx"
                        :max-size="10240"
                        :on-success="handleSuccess"
                        :on-error="handleError"
                        :on-remove="handlerRemove"
                        :show-upload-list="true"
                        :default-file-list="formData[item.file] || []"
                        :on-preview="downLoad"
                        :before-upload="beforeUpload"
                      >
                        <Button @click="handleFileType(item['file'])" icon="ios-cloud-upload-outline">上传附件</Button>
                      </Upload>
                      <a
                        v-else
                        class="filename"
                        v-for="file in formData[item.file]"
                        :key="file.id"
                        @click="downLoad(file)"
                      >
                        {{ file.name }}
                      </a>
                    </div>
                  </Col>
                </Row>
              </div>
              <Row :gutter="10" v-for="indicator in item.indicatorItem" :key="indicator.label">
                <Col span="11">
                  <Form-item :label="indicator.label" :label-width="210" :prop="indicator.value">
                    <div slot="label" style="display: contents;">
                      {{ indicator.label }}
                      <Tooltip
                        v-if="indicator.tip"
                        transfer
                        max-width="800"
                        :content="indicator.tip"
                        placement="right"
                        slot
                      >
                        <Icon type="ios-help-circle" />
                      </Tooltip>
                    </div>
                    <InputNumber
                      v-if="indicator.type === 'number'"
                      :min="0"
                      :max="1000000000"
                      :precision="0"
                      :placeholder="indicator.placeholder"
                      v-model="formData[indicator.value]"
                      type="number"
                    />
                    <Input
                      v-if="indicator.type === 'textarea'"
                      :placeholder="indicator.placeholder || '请输入'"
                      v-model="formData[indicator.value]"
                      type="textarea"
                      :rows="4"
                    ></Input>
                  </Form-item>
                </Col>

                <Col span="8">
                  <Form-item :label="indicator.remarkLabel" :label-width="150" :prop="indicator.remarkValue">
                    <div slot="label" style="display: contents;">
                      {{ indicator.remarkLabel }}
                      <Tooltip
                        v-if="indicator.remarkTip"
                        transfer
                        max-width="800"
                        :content="indicator.remarkTip"
                        placement="right"
                        slot
                      >
                        <Icon type="ios-help-circle" />
                      </Tooltip>
                    </div>
                    <Input v-model="formData[indicator.remarkValue]" :placeholder="indicator.remarkPlaceholder" />
                  </Form-item>
                </Col>
                <Col span="5" v-if="indicator.showFile">
                  <div class="upload">
                    <Upload
                      v-if="!disabled"
                      ref="upload"
                      :action="uploadUrl"
                      :headers="uploadHeaders"
                      :data="uploadData"
                      accept=".xls,.xlsx"
                      :max-size="10240"
                      :on-success="handleSuccess"
                      :on-error="handleError"
                      :on-remove="handlerRemove"
                      :show-upload-list="true"
                      :default-file-list="formData[indicator.file] || []"
                      :on-preview="downLoad"
                      :before-upload="beforeUpload"
                    >
                      <Button @click="handleFileType(indicator['file'])" icon="ios-cloud-upload-outline"
                        >上传附件</Button
                      >
                    </Upload>
                    <a
                      v-else
                      class="filename"
                      v-for="file in formData[indicator.file]"
                      :key="file.id"
                      @click="downLoad(file)"
                    >
                      {{ file.name }}
                    </a>
                  </div>
                </Col>
              </Row>
            </div>
          </Form>
        </Col>
      </Row>
    </div>
  </div>
</template>

<script>
import downLoadModel from './downLoad.vue'
import coverApi from '@/api/cover'
import { FORM_DESC, RULE_VALIDATE } from './const'
import dataEleApi from '@/api/dataElement'
import * as XLSX from 'xlsx'
export default {
  components: {},
  props: {
    hiddenBtnGroup: {
      type: Boolean,
      default: false
    },
    isCreate: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    isView: {
      type: Boolean,
      default: false
    },
    showProcessButton: {
      type: Boolean,
      default: true
    },
    id: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      uploadHeaders: { authorization: localStorage.Authorization ? `Bearer ${localStorage.Authorization}` : '' },
      uploadUrl: dataEleApi.getDataUploadUrl(),
      uploadData: { bizId: '0' },
      formDesc: FORM_DESC,
      ruleValidate: RULE_VALIDATE,
      fileTypeList: '',
      formData: {
        processId: '',
        personalCustomerTotal: 0,
        personalCustomerTotalRemark: '',
        personalActiveCustomerCount: 0,
        personalActiveCustomerCountRemark: '',
        personalInactiveCustomerCount: 0,
        personalInactiveCustomerCountRemark: '',
        enterpriseCustomerTotal: 0,
        enterpriseCustomerTotalRemark: '',
        enterpriseStrategicCustomerCount: 0,
        enterpriseStrategicCustomerCountRemark: '',
        personalCustomerTagCount: 0,
        personalCustomerTagCountRemark: '',
        personalCustomerTagCountAttachment: [],
        enterpriseCustomerTagCount: 0,
        enterpriseCustomerTagCountRemark: '',
        enterpriseCustomerTagCountAttachment: [],
        personalCustomerDataScenarioCount: 0,
        personalCustomerDataScenarioCountRemark: '',
        enterpriseCustomerDataScenarioCount: 0,
        enterpriseCustomerDataScenarioCountRemark: '',
        dataManagementPolicyExists: '',
        dataManagementPolicyExistsRemark: '',
        customerDataScenarioAttachment: [],
        dataManagementSystemExists: '',
        dataManagementSystemExistsRemark: '',
        dataClassificationGradingExists: '',
        dataClassificationGradingExistsRemark: '',
        dataCrossBorderExists: '',
        dataCrossBorderExistsRemark: '',
        dataSecurityMeasuresImplemented: '',
        dataSecurityMeasuresImplementedRemark: '',
        customerDataApplicationDifficulty: '',
        customerDataApplicationDifficultyRemark: '',
        customerDataApplicationSuggestAction: '',
        customerDataApplicationSuggestActionRemark: ''
      },
      pageLoading: false,
      loading: false
    }
  },
  methods: {
    hide() {
      this.$emit('Close')
    },
    save() {
      const now = new Date()
      const params = {
        id: this.id,
        buCode: this.$store.state.userBuByDataEle.key,
        year: now.getFullYear()
      }
      // 处理后端数据格式
      this.formData.personalCustomerTagCountAttachment = JSON.stringify(
        this.formData.personalCustomerTagCountAttachment
      )
      this.formData.enterpriseCustomerTagCountAttachment = JSON.stringify(
        this.formData.enterpriseCustomerTagCountAttachment
      )
      this.formData.customerDataScenarioAttachment = JSON.stringify(this.formData.customerDataScenarioAttachment)
      const paramsData = this.isCreate ? { ...params, ...this.formData } : this.formData
      this.loading = true
      dataEleApi
        .updateData(paramsData)
        .then(res => {
          if (res.code === 200) {
            this.$message.success('保存成功')
            this.$emit('Close', 1)
          }
          this.loading = false
        })
        .catch(e => {
          this.loading = false
        })
    },
    submit() {
      this.$refs['formValidate'].validate(valid => {
        if (!valid) {
          return this.$message.error('请检查表单填写内容是否正确')
        }
        if (
          this.formData.personalCustomerTagCount > 0 &&
          this.formData.personalCustomerTagCountAttachment.length <= 0
        ) {
          return this.$message.error('请上传个人客户标签附件')
        }
        if (
          this.formData.enterpriseCustomerTagCount > 0 &&
          this.formData.enterpriseCustomerTagCountAttachment.length <= 0
        ) {
          return this.$message.error('请上传企业客户标签附件')
        }
        if (
          this.formData.personalCustomerDataScenarioCount + this.formData.enterpriseCustomerDataScenarioCount > 0 &&
          this.formData.customerDataScenarioAttachment.length <= 0
        ) {
          return this.$message.error('请上传客户数据应用附件')
        }
        const now = new Date()
        let host = location.host
        if (host.includes('sit')) {
          host = 'crinfo-uat.test.crcloud.com'
        }
        // let pcUrl = encodeURIComponent(`https://${host}/form.html?type=dataElements&id=`)
        let pcUrl = `https://${host}/form.html?type=dataElements&id=`
        const params = {
          buCode: this.$store.state.userBuByDataEle.key,
          year: now.getFullYear()
        }
        // 处理后端数据格式
        this.formData.personalCustomerTagCountAttachment = JSON.stringify(
          this.formData.personalCustomerTagCountAttachment
        )
        this.formData.enterpriseCustomerTagCountAttachment = JSON.stringify(
          this.formData.enterpriseCustomerTagCountAttachment
        )
        this.formData.customerDataScenarioAttachment = JSON.stringify(this.formData.customerDataScenarioAttachment)
        const paramsData = this.isCreate ? { ...params, ...this.formData, pcUrl } : { ...this.formData, pcUrl }
        // console.log(paramsData)
        this.loading = true
        dataEleApi
          .insertData(paramsData)
          .then(res => {
            if (res.code === 200) {
              this.$message.success('提交成功')
              this.$emit('Close', 1)
            }
            this.loading = false
          })
          .catch(e => {
            this.loading = false
          })
      })
    },
    goApproval() {
      coverApi.getProcessUrl({ id: this.formData.processId, deviceType: 'PC' }).then(res => {
        window.open(res.data.data)
      })
    },
    setValue(type) {
      const obj = { customerTotal: this.customerTotal, tagTotal: this.tagTotal, dataTotal: this.dataTotal }
      return obj[type]
    },
    handleFileType(type) {
      this.fileTypeList = type
    },
    handleSuccess(response, file, fileList) {
      this.formData[this.fileTypeList].push({ name: file.name, fileId: response.data })
      this.$message.success('上传成功')
    },
    handlerRemove(file, fileList) {
      let index = this.formData[this.fileTypeList].findIndex(item => item.fileId === file.fileId)
      this.formData[this.fileTypeList].splice(index, 1)
    },
    handleError(err, file, fileList) {
      // 文件上传失败的回调函数，可以在这里处理上传失败的情况
      this.$message.error('上传失败')
    },
    // 表头校验
    uploadFile(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsArrayBuffer(file)
        reader.onload = e => {
          const data = new Uint8Array(e.target.result)
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const headers = XLSX.utils.sheet_to_json(worksheet, { header: 1 })[0]
          // 预期的表头格式
          const expectedHeaders1 = ['序号', '标签类别', '标签名称', '标签描述', '有值率', '备注']
          const expectedHeaders2 = ['序号', '场景类型', '落地情况', '场景名称', '场景说明', '价值成效', '备注']
          // 不同上传附件按钮匹配不同表头
          const expectedHeadersType = {
            personalCustomerTagCountAttachment: expectedHeaders1,
            enterpriseCustomerTagCountAttachment: expectedHeaders1,
            customerDataScenarioAttachment: expectedHeaders2
          }
          if (JSON.stringify(headers.sort()) === JSON.stringify(expectedHeadersType[this.fileTypeList].sort())) {
            resolve(true)
          } else {
            this.$message.error({
              content: '表头格式不正确',
              duration: 2
            })
            reject(false)
          }
        }
      })
    },
    async beforeUpload(file) {
      const res = await this.uploadFile(file)
      return res
    },
    downLoad(file) {
      coverApi.plantaskDownloadFile(file.fileId)
    },
    downLoadModel() {
      new this.$pageModal(
        downLoadModel,
        {
          props: {}
        },
        data => {}
      )
    }
  },
  computed: {
    customerTotal() {
      return this.formData.personalCustomerTotal + this.formData.enterpriseCustomerTotal
    },
    tagTotal() {
      return this.formData.personalCustomerTagCount + this.formData.enterpriseCustomerTagCount
    },
    dataTotal() {
      return this.formData.personalCustomerDataScenarioCount + this.formData.enterpriseCustomerDataScenarioCount
    }
  },
  created() {
    this.pageLoading = true
    // this.edit = !this.disabledPage
    if (this.id) {
      dataEleApi.getDataById({ id: this.id }).then(res => {
        // 处理后端附件数据格式问题
        res.data.personalCustomerTagCountAttachment = JSON.parse(res.data.personalCustomerTagCountAttachment)
        res.data.enterpriseCustomerTagCountAttachment = JSON.parse(res.data.enterpriseCustomerTagCountAttachment)
        res.data.customerDataScenarioAttachment = JSON.parse(res.data.customerDataScenarioAttachment)
        this.formData = res.data
        this.pageLoading = false
      })
    } else {
      this.pageLoading = false
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.ivu-input-number {
  width: 100%;
}
/deep/.ivu-upload {
  display: flex;
  flex-direction: row;
  // align-items: center;
  .ivu-upload-list {
    display: flex;
    margin-top: -12px;
  }
}
.upload {
  text-align: left;
}

.filename :hover {
  cursor: auto;
}

.data-edit-box {
  // display: flex;
  // overflow: hidden;
  // flex-direction: column;
  // height: 100%;
  margin: 20px;
  .data-page-header {
    display: flex;
    justify-content: space-between;
    padding: 15px 0;
    height: 60px;
    .header-title {
      font-size: 18px;
      font-weight: bold;
    }
  }
  .data-edit-content {
    overflow-x: hidden;
    overflow-y: scroll;
    padding-left: 80px;
    .indicatorItem {
      .titleItem {
        /deep/.ivu-form-item-label {
          font-size: 18px;
          font-weight: bold;
          padding-top: 6px;
          display: flex;
          justify-content: flex-end;
          align-items: center;
          &::before {
            display: inline-block;
            margin-right: 6px;
            content: '';
            width: 6px;
            height: 26px;
            background: var(--primary-color);
          }
        }
        // /deep/.ivu-form-item-content {
        //   padding-top: 4px;
        // }
        // display: flex;
        // align-items: center;
        // margin-bottom: 20px;
        .indicatorName {
          width: 178px;
          display: flex;
          // flex-basis: 400px;
          margin-right: 5px;
        }
        .indicatorInput {
          flex-basis: 328px;
          margin: 0 16px;
        }
      }
      // .indicatorName {
      //   //padding-left: 30px;
      //   font-size: 16px;
      //   font-weight: bold;
      //   &::before {
      //     display: inline-block;
      //     margin-right: 6px;
      //     content: '';
      //     width: 6px;
      //     height: 26px;
      //     background: var(--primary-color);
      //   }
      // }
    }
  }
}
</style>
